import qs from 'qs';
import request from 'umi-request';
import { Icon, message, Upload, Spin } from 'antd';
import { createUploadUsingPOST, createFileDeleteUsingDelete } from '@/services/upload';
import _ from 'lodash';
import React, { useState } from 'react';

const fileTypeArr = [
  'txt',
  'doc',
  'wps',
  'docx',
  'xls',
  'xlsx',
  'xlsm',
  'ppt',
  'pptx',
  'gif',
  'jpg',
  'JPG',
  'png',
  'psd',
  'bmp',
  'pdf',
  'rar',
  'zip',
];
const fileTypeCodeArr = [
  '3',
  '3',
  '3',
  '3',
  '3',
  '3',
  '3',
  '3',
  '3',
  '32',
  '32',
  '32',
  '39',
  '32',
  '34',
  '19',
  '19',
];

// 附件
export default function FilePage({ handleFile, fileList, isEdit }) {
  const [fileLoading, setFileLoading] = useState(false);
  const [viewLoading, setViewLoading] = useState(false);
  const [fileId, setFileId] = useState(null);
  const [fileError, setFileError] = useState('');
  if (!isEdit && _.isEmpty(fileList)) return <></>;
  // 上传文件
  const handleUpload = file => {
    setFileLoading(true);
    // 不允许上传大于20M的文件
    if (file.size > 20480000) {
      message.warning('单个文件最大上传20M.');
      setFileLoading(false);
      return null;
    }
    const fromData = new FormData();
    fromData.append('file', file);
    createUploadUsingPOST({ data: fromData })
      .then(res => {
        if (res && res.code === 1) {
          const cloneFileList = fileList || [];
          handleFile([
            ...cloneFileList,
            {
              uid: res.data.fileId,
              name: res.data.fileName,
              filePath: res.data.filePath,
              previewUrl: res.data.previewUrl,
              status: 'done',
            },
          ]);
        }
      })
      .then(() => setFileLoading(false));
    return null;
  };
  // 删除文件
  const handleRemove = ({ uid }) => {
    createFileDeleteUsingDelete({ params: { fileId: uid } }).then(res => {
      if (res && res.code === 1) {
        const newFileList = _.filter(fileList, item => item.uid !== uid);
        handleFile(newFileList);
      }
    });
  };
  // 下载文件
  const handleDownload = ({ uid }) => {
    const sessionToken = localStorage.getItem('sessionToken');
    const exportQueryString = qs.stringify({ fileId: uid, sessionToken });
    window.open(`${process.env.apiUrl}/api/v1/fileUpload/download?${exportQueryString}`);
  };
  // 查看文件
  const handleFileView = async ({ uid, name }) => {
    setFileError('');
    setViewLoading(true);
    setFileId(uid);
    if (!name || name === '') {
      setFileError('文件名称不符！');
    } else {
      const lastLen = name.lastIndexOf('.');
      const len = name.length;
      const suffix = name.substring(lastLen + 1, len);
      const fileTypeIndex = fileTypeArr.indexOf(suffix);
      if (fileTypeIndex > -1) {
        const convertType = fileTypeCodeArr[fileTypeIndex];
        const params = {
          downloadUrl: `${process.env.apiUrl}/api/v1/fileUpload/download?fileId=${uid}`,
          convertType,
          isDelSrc: '1',
        };
        if (fileTypeArr[fileTypeIndex] === 'rar') {
          params.isRar5 = '1';
        }
        await request('/docview/dcs/', {
          method: 'post',
          params,
        })
          .then(response => {
            if (response && response.result === 0) {
              const url = _.last(response.data);
              window.open(url);
            } else setFileError(response.message);
          })
          .catch(() => {
            setFileError('预览失败！');
          });
      } else setFileError('文件格式不支持预览！');
    }
    setViewLoading(false);
  };
  return (
    <div className="approve-box-content-paragraph">
      <div className="approve-box-content-paragraph-title">附件</div>
      {isEdit ? (
        <Spin spinning={fileLoading}>
          <Upload.Dragger
            name="file"
            action={handleUpload}
            onRemove={handleRemove}
            onDownload={handleDownload}
            disabled={fileLoading}
            fileList={fileList}
          >
            <p className="ant-upload-drag-icon">
              <Icon type="inbox" />
            </p>
            <p className="ant-upload-text">点击或将文件拖拽到这里上传</p>
            <p className="ant-upload-hint">单个文件最大上传20M</p>
          </Upload.Dragger>
        </Spin>
      ) : (
        <>
          {_.map(fileList, item => (
            <div className="approve-box-content-paragraph-file">
              <div>
                <Icon type="paper-clip" />
                &nbsp; &nbsp;
                <span>{item.name}</span>&nbsp; &nbsp;
                {item.uid === fileId && (
                  <>
                    {viewLoading && <Icon type="loading" />}
                    <span className="approve-box-content-paragraph-file-error">{fileError}</span>
                  </>
                )}
              </div>
              <div>
                <Icon type="eye" onClick={() => handleFileView(item)} />
                &nbsp;&nbsp;
                <Icon type="download" onClick={() => handleDownload(item)} />
              </div>
            </div>
          ))}
        </>
      )}
    </div>
  );
}
